package cn.bellychang.leetcode.question104;

import java.util.LinkedList;

/**
 * @author ChangLiang
 * @date 2021/3/7
 */
public class Solution3 {

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int height = 0;
        int levelSize = 1;
        int currentSize = 0;
        LinkedList<TreeNode> queue = new LinkedList();
        queue.add(root);
        int nextLevelSize = 0;
        while (true) {
            TreeNode node = queue.remove();
            currentSize++;
            if (node.left != null) {
                nextLevelSize++;
                queue.add(node.left);
            }
            if (node.right != null) {
                nextLevelSize++;
                queue.add(node.right);
            }
            if (currentSize == levelSize) {
                currentSize = 0;
                levelSize = nextLevelSize;
                nextLevelSize = 0;
                height++;
            }
            if (queue.size() == 0) {
                break;
            }
        }
        return height;
    }
}
